package com.xms.schema.service.entity;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xms.datacore.IMetadataProvider;
import com.xms.datacore.service.DeleterService;
import com.xms.dependency.XmsDependencyException;
import com.xms.dependency.service.IDependencyChecker;
import com.xms.dependency.service.IDependencyDeleterService;
import com.xms.event.core.AuthorizationStateChangedEvent;
import com.xms.event.core.IEventPublisher;
import com.xms.schema.core.EntityDefaults;
import com.xms.schema.entity.Entity;
import com.xms.schema.event.EntityMetaDeletedEvent;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * EntityDeleterService
 * </p>
 *
 * @author migo
 * @since 2021/9/2
 */
@CacheConfig(cacheNames = "schema.entity", keyGenerator = "CacheKeyGenerator")
@Service
public class EntityDeleterService extends DeleterService<Entity> implements IEntityDeleterService {
    private IMetadataProvider _metadataProvider;
    private IDependencyDeleterService _dependencyDeleterService;
    private IDependencyChecker _dependencyChecker;
    private IEventPublisher _eventPublisher;

    @Autowired
    public EntityDeleterService(IMetadataProvider metadataProvider,
                                IDependencyDeleterService dependencyDeleterService,
                                IDependencyChecker dependencyChecker,
                                IEventPublisher eventPublisher) {
        _metadataProvider = metadataProvider;
        _dependencyDeleterService = dependencyDeleterService;
        _dependencyChecker = dependencyChecker;
        _eventPublisher = eventPublisher;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean delete(Entity deleted, boolean dropTable) throws SQLException, XmsDependencyException {
        if (deleted != null) {
            //基础实体不允许删除
            if (!deleted.getIscustomizable()) {
                return false;
            }
            UUID id = deleted.getEntityid();
            //检查依赖项
            _dependencyChecker.checkAndThrow(EntityDefaults.MODULE_NAME, id);
            //执行删除
            boolean success = super.deleteById(id);
            if (success) {
                if (dropTable) {
                    //删除物理表
                    _metadataProvider.dropView(deleted);
                    _metadataProvider.dropTable(deleted);
                }
                //删除依赖项
                _dependencyDeleterService.deleteByDependentId(EntityDefaults.MODULE_NAME, deleted.getEntityid());
                //权限更改事件
                _eventPublisher.publish(new AuthorizationStateChangedEvent(EntityDefaults.MODULE_NAME, Collections.singletonList(id), false));
                //删除事件
                _eventPublisher.publish(new EntityMetaDeletedEvent(EntityDefaults.MODULE_NAME, deleted));
                return true;
            }
        }
        return false;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean delete(Entity deleted) throws SQLException, XmsDependencyException {
        return this.delete(deleted, true);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean deleteByName(String name, boolean dropTable) throws SQLException, XmsDependencyException {
        LambdaQueryWrapper<Entity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Entity::getName, name);
        Entity deleted = super.getOne(queryWrapper);
        return this.delete(deleted, dropTable);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean deleteById(UUID id, boolean dropTable) throws SQLException, XmsDependencyException {
        Entity deleted = super.getById(id);
        return this.delete(deleted, dropTable);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean deleteByIds(Collection<UUID> idList, boolean dropTable) throws SQLException, XmsDependencyException {
        if (CollectionUtil.isEmpty(idList)) {
            return false;
        }
        List<Entity> deleteds = super.listByIds(idList);
        if (CollectionUtil.notEmpty(deleteds)) {
            for (Entity entity : deleteds) {
                this.delete(entity, dropTable);
            }
            return true;
        }
        return false;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean deleteByName(String name) throws SQLException, XmsDependencyException {
        return this.deleteByName(name, true);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean deleteById(UUID id) throws SQLException, XmsDependencyException {
        return this.deleteById(id, true);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean deleteMany(Wrapper<Entity> queryWrapper) throws XmsDependencyException, SQLException {
        List<Entity> deleteds = super.list(queryWrapper);
        if (CollectionUtil.notEmpty(deleteds)) {
            for (Entity entity : deleteds) {
                this.delete(entity);
            }
            return true;
        }
        return false;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean deleteByIds(Collection<UUID> idList) throws XmsDependencyException, SQLException {
        return this.deleteByIds(idList, true);
    }
}
